package com.live.shop.tool;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.live.shop.model.AudioFileModel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public final class FileUtils {
    public static List<AudioFileModel> getMisicList(Context context){
        // 媒体库查询语句（写一个工具类MusicUtils）
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,
                null, "date_added DESC");
        List<AudioFileModel> list = new ArrayList<>();
        if (cursor != null) {
            while (cursor.moveToNext()) {
                AudioFileModel model = new AudioFileModel();
                model.setId(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)));
                model.setTilte(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
                model.setAlbum(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)));
                model.setArtist(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)));
                model.setUrl(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));//绝对文件系统路径
                model.setDisplayName(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)));
                model.setDuration(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)) / 1000);
                model.setSize(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)));
                list.add(model);
            }
            // 释放资源
            cursor.close();
        }
        return list;
    }
    //判断文件是否存在
    public static boolean getFileExist(Context context, String filePath){
        if(filePath == null || filePath.isEmpty()){
            return false;
        }
        if(new File(filePath).exists() && !filePath.contains("content://")){
            return true;
        }
        if(filePath.contains("content://")){
            Uri uri = Uri.parse(filePath);
            String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
            Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                // 文件存在
                cursor.close();
                return true;
            } else {
                // 文件不存在
                return false;
            }
        }
        return false;
    }

}
